package com.zerotwo.exam.user.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @author 小七
 * @version 1.0
 * @date 2024/5/28-10:40
 * @description 阿里云OSS工具类
 */
@Component
public class AliOSSUtils {
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tM6N3CkxViKonz5vXjp";
    private String accessKeySecret = "1IsmDdIERFhLXfNEqj0zu1pmxq0mHh";
    private String bucketName = "zerotwo-aikao";

    public String upload(MultipartFile multipartFile) throws IOException {
        //获取上传文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        //避免文件覆盖
        String filename = LocalDateTime.now().toString()+multipartFile.getOriginalFilename();

        //上传到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName,filename,inputStream);

        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+filename;
        //关闭ossClient
        ossClient.shutdown();
        return url;
    }
}
